/**
 * @author {Yuntao Zhou}
 */
var NewsCustomView=function(config){
    this.el=null;
    this.$iptName=null;
    this.$iptFilter=null;
    this.$chkSelect=null;
    this.$sourceTip=null;
    this.win=null;
    this.regionData=null;
    this.regionCBtn=null;
    this.sourceGrid=null;
    this.newsObj=null;//current News obj
    this.viewID=0;//current view id
    this.selectRegion={};//store the select region
    this.selectSource={};//store the select source
    this.maps={};
    this.sourceList=null;//store all source list by region search
    this.visibleSourceList=null;//store visible source list
    this.name=null;//current view name
    this.timer=null;
    this.sTimer=null;
    this.delay=500;
    this.scrollPN=null;
    this.allChecked=false;
    this.html='<div class="rtq-news-ctview"><div class="row filter-list"><h3>Filters Applied:</h3><div><div class="filter-content"></div></div></div>'+
                '<div class="row region-list"><h3 class="region-title">Region:</h3><div class="region-chk"></div></div>'+
                '<div class="viewbd"><div class="rtq-grid rtq-grid-auto source-list"><h3 class="source-title">Filter by Sources:</h3><div class="nv-grid-hd"></div><div class="nv-input">'+
                '<a class="rtq-checkbox chk-all"></a><input type="text" class="qs-ui-ipt ipt-source"/><input type="text" class="qs-ui-ipt ipt-country"/><input type="text" class="qs-ui-ipt ipt-type"/><input type="text" class="qs-ui-ipt ipt-category"/>'
                +'</div><div class="nv-grid-bd"></div></div>'+
                '<div class="row viewname"><h3 class="name-title">Custom View Name</h3><input value="" class="qs-ui-ipt ipt-name"/></div>'+
                '<div class="action"><a class="qs-ui-btn save" href="javascript:void(0)">Save</a><a class="qs-ui-btn close" href="javascript:void(0)">Close</a></div></div></div>';
    this.config={};
    $.extend(this.config,config);
    this.init();
};
NewsCustomView.prototype={
    init:function(){
        this.el=$(this.html);
        this.$iptName=this.el.find('.ipt-name');
        this.$iptFilter=this.el.find('.nv-input input');
        this.$chkSelect=this.el.find('.nv-input a');
        this.$sourceTipContainer=this.el.find('.filter-content');
        this.regionData=[{
            "txt": "Africa",
            "val": "LR/afr"
        }, {
            "txt": "Americas",
            "val": "LR/am"
        }, {
            "txt": "Antarctica",
            "val": "LR/an"
        }, {
            "txt": "Asia",
            "val": "LR/as"
        }, {
            "txt": "Europe",
            "val": "LR/eur"
        }, {
            "txt": "Oceania",
            "val": "LR/oc"
        }, {
            "txt": "Global",
            "val": "LR/glb"
        }];
        this.cols=[{
            header: '',
            dataIndex: 'check',
            renderer: function(val){
                return '<a class="rtq-checkbox '+(val?'rtq-checkbox-on':'')+'" href="javascript:void(0)"></a>';
            },
            width: '5%'
        },{
            header:'Source Name',
            dataIndex:'name',
            width:'30%'
        },{
            header:'Country',
            dataIndex:'country',
            width:'15%'
        },{
            header:'Type',
            dataIndex:'type',
            width:'25%'
        },{
            header:'Category',
            dataIndex:'cat',
            width:'25%'
        }, {
            header: 'id',
            dataIndex: 'id',
            hide: true,
            width:'0'
        }];
        this._resizeInputWidth();
        this._createRegionList(this.regionData,this.el.find('.region-chk'));
        this._createSourceGrid(this.el.find('.nv-grid-hd'),this.el.find('.nv-grid-bd'),444,190,this.cols);
        this._createWindow(this.el);
        this._createFilterScrollPN();
        this._bindEvent();
    },
    _createFilterScrollPN:function(){
        this.scrollPN=new Util.ScrollPanel(this.$sourceTipContainer,{showX:false});
    },
    _resizeInputWidth:function(w0,w1,w2,w3,w4){
        w0=w0?w0:15;
        w1=w1?w1:130;
        w2=w2?w2:65;
        w3=w3?w3:110;
        w4=w4?w4:110;
        this.$chkSelect.css('marginRight',w0-14);
        this.$iptFilter.eq(0).css('width',w1);
        this.$iptFilter.eq(1).css('width',w2);
        this.$iptFilter.eq(2).css('width',w3);
        this.$iptFilter.eq(3).css('width',w4);
    },
    _createRegionList:function(data,container){
        var self=this;
        this.regionCBtn = new Util.ButtonGroup(container,data, {
            onClick: function(v){
                if (self.selectRegion[v]) {
                    delete self.selectRegion[v];
                }else {
                    self.selectRegion[v] = true;
                }
                if (self.sTimer) {
                    clearTimeout(self.sTimer);
                    self.sTimer = 0;
                }
                self.sTimer = setTimeout(function(){
                    self._searchSourceListByRegion();
                }, self.delay);
            }
        },{type:'checkbox'});
    },
    _createSourceGrid:function(hcontainer,bcontainer,w,h,cols){
        var self=this;
        this.sourceGrid=new Util.DataGrid(bcontainer,{},{
            width:w,
            height:h,
            column:cols,
            indexColKey: 'id',
            outSideHeader:true,
            autoWidth:true,
            rowLayout: 'list',
            rowDragable: false,
            rowDropable: false,
            sortable:false,
            cellResize:false,
            cellRearrange:false
        },{
            onRowSelected:function(e, row){
                var $chk=$(row.DOMMap['check']).find('a');
                $chk.toggleClass('rtq-checkbox-on');
                if($chk.hasClass('rtq-checkbox-on')){
                    self._createSourceTip([row.data]);
                }else{
                    self._removeSourceTip(row.id);
                }
                self.resizeFilterContainer(null,50);
                self.changeAllCheckState();
            }
        });
        this.sourceGrid.header.el.appendTo(hcontainer);
    },
    changeAllCheckState:function(){
//      this.$chkSelect.removeClass('rtq-checkbox-on');
//      if(this._getSelectSourceLength()==this.sourceList.length){
//          this.allChecked=true;
//          this.$chkSelect.addClass('rtq-checkbox-on');
//      }else{
//          this.allChecked=false;
//      }
        this.$chkSelect.removeClass('rtq-checkbox-on');
        this.allChecked=true;
        for(var i=0,l=this.visibleSourceList.length;i<l;i++){
            if(!this.selectSource[this.visibleSourceList[i].id]){
                this.allChecked=false;
                break;
            }
        }
        if(this.allChecked){
            this.$chkSelect.addClass('rtq-checkbox-on');
        }
    },
    _getSelectSourceLength:function(){
        var count=0;
        for(var s in this.selectSource){
            count++;
        }
        return count;
    },
    _selectAllSource:function(){
        if (this.visibleSourceList != null && this.visibleSourceList.length != 0) {
            this._unSelectAllSource();
            this.sourceGrid.body.find('.rtq-checkbox').addClass('rtq-checkbox-on');
            this._createSourceTip(this.visibleSourceList);
        }
    },
    _unSelectAllSource:function(){
        if (this._getSelectSourceLength()!=0) {
            this.sourceGrid.body.find('.rtq-checkbox').removeClass('rtq-checkbox-on');
            this.selectSource={};
            this.$sourceTipContainer.empty();
        }
    },
    _removeSourceTip:function(id){
        delete this.selectSource[id];
        this.$sourceTipContainer.find('a[val='+id+']').remove();
        if(this.sourceGrid.DOMMap[id]){
            $(this.sourceGrid.DOMMap[id]['check']).find('a').removeClass('rtq-checkbox-on');
        }
        this.changeAllCheckState();
    },
    _createSourceTip:function(list){
        var self=this,html='';
        var len=list.length;
        for(var i=0;i<len;i++){
            //this.selectSource[list[i].id]=list[i]["pn"];
            name=this._getTipName(list[i]);
            this.selectSource[list[i].id]=[name,list[i].from];
            html+='<a class="nv-source-tip" val="'+list[i].id+'">'+name+', </a>';
        }
        this.$sourceTipContainer[0].innerHTML+=html;            
    },
    reCreateSourceTip:function(){
        var html='';
        this.$sourceTipContainer[0].innerHTML='';
        for(var s in this.selectSource){
            html+='<a class="nv-source-tip" val="'+s+'">'+this.selectSource[s][0]+', </a>';
        }
        this.$sourceTipContainer[0].innerHTML+=html;
        this.resizeFilterContainer(null,50);
    },
    _getTipName:function(data){
        return data.cat;
    },
    _createWindow:function(html){
        var self=this;
        this.win= new Util.RtqWindow(document.body, {
            windowReady: function(obj){
                obj.setHtml(html);
                obj.el.find('.action .close').bind('click',function(e){
                    obj.hide();
                });
                obj.el.find('.action .save').bind('click',function(e){
                    self.save();
                });
            },
            beforeClosed: function(){
            },
            onResized:function(win, width, height){
                self.sourceGrid.resize(width-6, height-270);
                var $cell=self.sourceGrid.header.el.find('.rtq-grid-cell');
                var w0=$cell.eq(0).width()-11;
                var w1=$cell.eq(1).width()-11;
                var w2=$cell.eq(2).width()-11;
                var w3=$cell.eq(3).width()-11;
                var w4=$cell.eq(4).width()-11;
                self._resizeInputWidth(w0,w1,w2,w3,w4);
                self.resizeFilterContainer(null,50);
            }
        }, {
            title: "Custom View - Untitled",
            top:100,
            width: 500,
            height: 460,
            minWidth: 500,
            minHeight: 460,
            isGlobal:true,
            hasSettingPanel: false,
            closeAction: 'hide'
        }); 
        rtqWindowGroup.register(this.win);
        this.win.hide(); 
    },
    _bindEvent:function(){
        var self=this,
            $chkAll=this.el.find('.nv-input a'),
            $input=this.el.find('.nv-input input');
        $chkAll.bind('click',function(e){
            $chkAll.toggleClass('rtq-checkbox-on');
            if($chkAll.hasClass('rtq-checkbox-on')){
                self._selectAllSource();
            }else{
                self._unSelectAllSource();
            }
            self.resizeFilterContainer(null,50);
        });
        
        $input.bind('keyup',function(e){
            self.visibleSourceList=self.filterSourceByKey(self.$iptFilter);
            list=self.selectSourceList(self.visibleSourceList);
            if (self.timer) {
                clearTimeout(self.timer);
                self.timer = 0;
            }
            self.timer = setTimeout(function(){
                self.sourceGrid.reBindData(list);
                self.changeAllCheckState();
            }, self.delay);
        });
        
        this.$sourceTipContainer.bind('click.newsView',function(e){
            var target=$(e.target);
            var id=target.attr('val');
            if(target.hasClass('nv-source-tip')){
                self._removeSourceTip(id);
                self.resizeFilterContainer(null,50);
            }
        });
    },
    resizeFilterContainer:function(w,h){
        this.scrollPN.reSize(w,h);
        this.$sourceTipContainer.css({
            width: '100%'
        });
    },
    selectSourceList:function(list){//add the check dataIndex for the sourcelist
        for(var i=0,l=list.length;i<l;i++){
            if(this.selectSource[list[i].id]){
                list[i]['check']=true;
            }else{
                list[i]['check']=false;
            }
        }
        return list;
    },
    reBindData:function(data){
        this.sourceList=data;
        this.sourceGrid.reBindData(data);
    },
    filterSourceByKey:function($input){
        var sourceKey=$input.eq(0).val(),
            countryKey=$input.eq(1).val(),
            typeKey=$input.eq(2).val(),
            categoryKey=$input.eq(3).val();
        //filter rule
        if(this.sourceList==null){
            return;
        }
        var len=this.sourceList.length,
            flag,sFlag=false,tFlag=false,cFlag=false,caFlag=false,
            source,filterSourceList=[];
        if(sourceKey&&sourceKey!=null&&sourceKey.length>0){
            sFlag=true;
        }if(typeKey&&typeKey!=null&&typeKey.length>0){
            tFlag=true;
        }if(countryKey&&countryKey!=null&&countryKey.length>0){
            cFlag=true;
        }if(categoryKey&&categoryKey!=null&&categoryKey.length>0){
            caFlag=true;
        }
        if (!sFlag && !tFlag && !cFlag&&!caFlag) {
            filterSourceList=this.sourceList;
        }
        else {
            for (var i = 0; i < len; i++) {
                source = this.sourceList[i];
                flag = false;
                if (sFlag) {
                    if (!this._isContains(source['name'],sourceKey)) {
                        continue;
                    }
                    else {
                        flag = true;
                    }
                }
                if (cFlag) {
                    if (!this._isContains(source['country'],countryKey)){
                        continue;
                    }
                    else {
                        flag = true;
                    }
                }
                if (tFlag) {
                    if (!this._isContains(source['type'],typeKey)) {
                        continue;
                    }
                    else {
                        flag = true;
                    }
                }
                if (caFlag) {
                    if (!this._isContains(source['cat'],categoryKey)){
                        continue;
                    }
                    else {
                        flag = true;
                    }
                }
                if (flag) {
                    filterSourceList.push(source);
                }
            }
        }
        return filterSourceList;
    },
    _isStartWith:function(str,s){
        if(str.length==0||str.length<s||!str||!s||s.length==0||!str){
            return false;
        }else if(str.substring(0,s.length).toLowerCase()==s.toLowerCase()){
            return true;
        }else{
            return false;
        }
    },
    _isContains:function(str,s){
        //if(str.length==0||str.length<s||!str||!s||s.length==0||!str){
        if(str.length==0||str.length<s.length||!str||!s||s.length==0||!str){  //fix bug #1207 - david
            return false;
        }else if(str.toLowerCase().indexOf(s.toLowerCase())>-1){
            return true;
        }else{
            return false;
        }
    },
    _getExcludeSource:function(){
//      var dcSourceList=QSPC.getConfig(2)["dcSourceList"];
//      var ntSourceList=QSPC.getConfig(2)["ntSourceList"];
        var ntSourceList={},dcSourceList={};
        if (GB_NewsDataManager.sourcePermission) {
            ntSourceList = GB_NewsDataManager.sourcePermission.ntSourceList || {};
            dcSourceList = GB_NewsDataManager.sourcePermission.dcSourceList || {};
        }
        var dcSources=[],ntSources=[];
        for(var i in dcSourceList){
            if(dcSourceList[i]===false){
                dcSources.push(i);
            }
        }
        for(var i in ntSourceList){
            if(ntSourceList[i]===false){
                ntSources.push(i);
            }
        }
        return {
            'nt':ntSources.join(','),
            'dc':dcSources.join(',')
        }
    },
    _searchSourceListByRegion:function(ids){    
        var self=this,str='';
        self._emptySourceList();
        self._emptySelectSource();
        for(var r in this.selectRegion){
            str+=r+',';
        }
        str=str.substring(0,str.length-1);
        var ntSources=this._getExcludeSource()['nt'];
        var dcSources=this._getExcludeSource()['dc'];
        if (str.length == 0) {
            return;
        }else {
            GB_NewsDataManager.getNewsSourceList({
                region: str,
                ntSources:ntSources,
                dcSources:dcSources,
                productCode:'QS'
            }, function(data){
                if (data == null || !data) {
                    return;
                }
                data = $.evalJSON(data);
                if (data.length != 0) {
                    self.sourceList = data;    
                    self._setPermissionSource(data,ids);                    
                    self.visibleSourceList=self.filterSourceByKey(self.$iptFilter);
                    if (self._getSelectSourceLength() != 0) {
                        self.changeAllCheckState();//check all
                        self.visibleSourceList = self.selectSourceList(self.visibleSourceList);//add check for the data
                    }
                    self.reCreateSourceTip();
                    self.sourceGrid.reBindData(self.visibleSourceList);
                }
            });
        }
    },
    _setPermissionSource:function(list,ids){
        var sourceList={};
        var ntSourceList={},dcSourceList={};
        if (GB_NewsDataManager.sourcePermission) {
            ntSourceList = GB_NewsDataManager.sourcePermission.ntSourceList || {};
            dcSourceList = GB_NewsDataManager.sourcePermission.dcSourceList || {};
        }
        $.extend(sourceList,dcSourceList,ntSourceList);
        for(var i=0,l=list.length;i<l;i++){
            data=list[i];
            if(!sourceList.hasOwnProperty([data.id])||sourceList[data.id]===true){
                if(typeof ids!='undefined'){
                    if(GB_NewsDataManager.inArray(data.id,ids)>-1){
                        this.selectSource[data.id]=[this._getTipName(data),data.from];    
                    }
                }   
            }   
        }
    },  
    _initRegion:function(){//select region ButtonGroup
        for(var i in this.regionCBtn.btns){
            if(this.selectRegion[i]){
                this.regionCBtn.btns[i].select();
            }else{
                this.regionCBtn.btns[i].inverse();
            }   
        }
        
    },
    _emptySourceList:function(){
        this.sourceList=[];
        this.visibleSourceList=[];
        this.sourceGrid.empty();        
    },
    _emptySelectSource:function(isEmpty){
        isEmpty===false?false:true;
        if (isEmpty) {
            this.selectSource = {};
            this.$sourceTipContainer[0].innerHTML = '';
            this.$chkSelect.removeClass('rtq-checkbox-on');
        }
    },
    _checkName:function(name){
        var flag=true;     
        for (var i = 0,l=GB_NewsDataManager.defaultViewList.length; i < l; i++) {
            if (name == GB_NewsDataManager.defaultViewList[i].txt&&this.viewID!=GB_NewsDataManager.defaultViewList[i].vid) {
                flag=false;
                break;
            }
        }
        return flag;
    },
	getShareViewMaxIndex:function(type,name){
		var viewlist=GB_NewsDataManager.defaultViewList;
        if (type != GB_NewsDataManager.DEFAULT_TYPE) {
			viewlist=GB_NewsDataManager.briefingViewList;
		}
		var temp=0,custom=null,index=0,reg= /^Share:(.*)\_(\d*)(?=$)/;   
		for(var i=viewlist.length-1;i>=0;i--){
			custom=viewlist[i],temp = reg.exec(custom.txt);
			if(temp&&temp.length==3){
				if(temp[1]==$.trim(name)&&!isNaN(temp[2])){
					index=Math.max(index,temp[2]);
				}
			}
		}
        return index;
	},
	checkName:function(type,name){
		var flag=true,viewlist=GB_NewsDataManager.defaultViewList;
        if (type != GB_NewsDataManager.DEFAULT_TYPE) {
			viewlist=GB_NewsDataManager.briefingViewList;
		}
		for (var i = 0,l=viewlist.length; i < l; i++) {
			if (name == viewlist[i].txt) {
				flag=false;
				break;
			}
		}
        return flag;
    },
	getID:function(type,name){
		var viewlist=GB_NewsDataManager.defaultViewList;
        if (type != GB_NewsDataManager.DEFAULT_TYPE) {
			viewlist=GB_NewsDataManager.briefingViewList;
		}
		for (var i = 0,l=viewlist.length; i < l; i++) {
			if (name == viewlist[i].txt) {
				return viewlist[i].vid;
			}
		}
        return null;
	},
    create:function(newsObj){//create a new View
        this.newsObj=newsObj;
        this.empty();
        this.win.setTitle("Custom View - Untitled");
        this.selectRegion={
            "LR/afr":true,
            "LR/am":true,
            "LR/an":true,
            "LR/as":true,
            "LR/eur":true,
            "LR/oc":true,
            "LR/glb":true
        };
        this._initRegion();
        this._searchSourceListByRegion();
        this.win.show();
    },
    edit:function(newsObj,id){
        var self=this;
        self.empty();
        self.newsObj=newsObj;
        self.viewID=id;
        GB_NewsDataManager.getViewSourceById(id,this.newsObj.profile.type,function(o){
            self.selectRegion=o.region;//get the view region
            self.$iptName.prop('readOnly', true).val(o.title);
            self.win.setTitle("Custom View - "+o.title);
            self.win.show();
            self._initRegion();
            self._searchSourceListByRegion(o.ntSource.concat(o.dcSource));
        }); 
    },
    save:function(){
        var self=this;
        this.name = this.$iptName.val();
        if (this.name == '') {
            Util.alert('Please enter a name.');
        }else{
			if (!QS_Validator.test(this.name, 'name')) {    
	            return;
	        }
            if (!this._checkName(this.name)) {
                Util.alert('The same View Name already exists. Please enter a different name.');
            }
            else {
                if (this._getSelectSourceLength() == 0) {
                    Util.alert('Please select a source.');
                }
                else {
                    var ntIds = [];
                    var dcIds = [];
                    for (var id in this.selectSource) {
                        if (this.selectSource[id][1] == 'NT') {
                            ntIds.push(id);
                        }
                        else 
                            if (this.selectSource[id][1] == 'DC') {
                                dcIds.push(id);
                            }
                    }
                    if (this.viewID > 0) {
                        GB_NewsDataManager.saveViewSource(this.viewID, {//save
                            region: this.selectRegion,
                            ntSource: ntIds,
                            dcSource: dcIds,
                            title: this.name
                        }, function(o){
                            self.callback(o);
                        });
                    }
                    else {
                        GB_NewsDataManager.createViewSource({//add
                            region: this.selectRegion,
                            ntSource: ntIds,
                            dcSource: dcIds,
                            title: this.name
                        }, function(o){
                            self.callback(o);
                        });
                    }
                }
            }
        }
    },
    remove:function(newsObj,id){
        Util.confirm('Are you sure you want to delete?', function(b){
            if (!b) {
                return;
            }
            var self=this;
            self.newsObj=newsObj;
            GB_NewsDataManager.deleteViewSource(id,function(o){
                if (o === true) {
                    GB_NewsDataManager.getViewList(self.newsObj.profile.type,function(data){
                        if (self.newsObj.settingPanel != null) {
                            self.newsObj.settingPanel.reBindViewMenu(data);
                        }
                        self.newsObj.closeView(id);
                        self.newsObj.openView(self.newsObj.openedList[0],self.newsObj.getViewName(self.newsObj.openedList[0]));//open default view Tab(id:-1)
                        workspaceManager.OpenFileWin.hide();
                    });
                }
            });
        });
        
    },
    show:function(){
        this.win.show();
    },
    empty:function(){
        this.viewID = 0;
        this.selectRegion={};
        this.selectSource={};
        this.sourceList=[];
        this.visibleSourceList=[];
        this.$iptName.prop('readOnly',false).val('');
        this.$iptFilter.val('');
        this.$chkSelect.removeClass('rtq-checkbox-on');
        this.$sourceTipContainer.empty();
        this.scrollPN.reSize(null,50);
        this.sourceGrid.empty();
        for(var i in this.regionCBtn.btns){
            this.regionCBtn.btns[i].inverse();
        }
    },
    callback:function(d){
        if(d===false){
            return;
        }
        var self=this;
        if (d == -1) {
            Util.alert('Custom View with the same name already exists. Please enter a different name.');
        }else{
            if(this.viewID>0){
                d=this.viewID;
            }else{
                d=parseInt(d,10);
            }
            GB_NewsDataManager.getViewList(this.newsObj.profile.type,function(o){
                if (self.newsObj.settingPanel != null) {
                    self.newsObj.settingPanel.reBindViewMenu(o);
                }
                if(self.newsObj.currentViewID==d||self.viewID==0){
                    self.newsObj.openView(d,self.name);//if edit view equals current view, or create a new view, open it
                }
                self.win.hide();
            });
        }   
    }
};

var GB_NewsCustomView=new NewsCustomView();
